//
//  WBTabBar.swift
//  Weibo
//
//  Created by xu on 2017/3/18.
//  Copyright © 2017年 xuantong. All rights reserved.
//

import UIKit

class WBTabBar: UITabBar {
    
    //定义闭包,将按钮点击事件发送出去,让控制器来做点击事件的处理
    var composrClosure:(()->())?
    
   override  init(frame: CGRect) {
        super.init(frame: frame)
     self.addSubview(composeButton)

    //按钮点击事件
    self.composeButton.addTarget(self, action: #selector(composrBtnDidClick), for: UIControlEvents.touchUpInside)
    
    }
    
    //按钮点击监听事件方法 
    //将按钮设置为私有的按钮private
    //@objc 是告诉系统这个方法或属性具备OC的特性(消息机制,kvc的动态派发)
   @objc private func composrBtnDidClick() {
        
        //点击的时候执行闭包
        composrClosure?()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //x修改内部视图的位置,应该重写layoutSubviews
    override func layoutSubviews() {
        super.layoutSubviews()
        
        
        //定义宽高
        let width = UIScreen.main.bounds.width/5
        let height = self.bounds.height
        
        var index = 0
        
        //遍历子视图, 获取uitabBr类型的控件,并进行修改
        for subView in subviews {
            
            //判断类型
            if subView.isKind(of: NSClassFromString("UITabBarButton")!) {
                
                subView.frame = CGRect(x: CGFloat(index) * width, y: 0, width: width, height: height)
                
                //index += 1
                index += (index == 1 ? 2: 1)
            }
        }
        
        
        composeButton.bounds.size = CGSize(width: width, height: height)
        composeButton.center = CGPoint(x: self.center.x, y: height*0.5)
        
    }
    
    
    //懒加载
    lazy var composeButton :UIButton = {
        
        let btn = UIButton()
       
        btn .setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for:.normal)
        btn .setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        
        //设置背景图片
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .highlighted)
        
        
        return btn

    }()
    
}
